package com.chenglu.android.common.utils;

import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.util.Patterns;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.chenglu.android.R;
import com.chenglu.android.common.net.RetrofitClient;
import com.chenglu.android.common.net.RetrofitClientCL;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @author lyj
 * @Created by Copyright © 2023 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description： 检验邮箱和电话号码工具类
 */
public class Utils {
    /**
     * 正则表达式：验证邮箱
     */
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";


    /**
     * 校验邮箱
     *
     * @param email
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isEmail(String email) {
        return Pattern.matches(REGEX_EMAIL, email);
    }

    /**
     * 查找一个布局里的所有的按钮并设置点击事件
     *
     * @param rootView
     * @param listener
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
    public static void findButtonAndSetOnClickListener(View rootView,
                                                       View.OnClickListener listener) {
        if (rootView instanceof ViewGroup) {
            ViewGroup parent = (ViewGroup) rootView;
            for (int i = 0; i < parent.getChildCount(); i++) {
                View child = parent.getChildAt(i);
                // 如果是按钮设置点击事件
                if (child instanceof Button || child instanceof ImageButton) {
                    // 没有设置过监听器才设置
                    if (!child.hasOnClickListeners())
                        child.setOnClickListener(listener); // 设置点击事件
                }
                if (child instanceof ViewGroup) {
                    findButtonAndSetOnClickListener(child, listener);
                }
            }
        }
    }


    /**
     * 格式化日期显示
     */
    public static String formatDate(long date) {
        if (DateUtils.isToday(date)) {
            return DateFormat.format("今天 kk:mm", date).toString();
        } else {
            return DateFormat.format("yyyy/MM/dd kk:mm", date).toString();
        }
    }

    /**
     * 格式化金额显示
     */
    public static String formatAmount(double amount) {
        NumberFormat format = NumberFormat.getCurrencyInstance();
        format.setMaximumFractionDigits(1);     // 金额只保存一位有效数字
        return format.format(amount);
    }

    /**
     * 匹配ip地址的正则表达式
     */
    private static final String IP_REGEXP =
            "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9" +
                    "])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\" +
                    ".(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\." +
                    "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])";

    /**
     * 替换一个url中的ip地址 <br/>
     * 例如：<br/>
     * url = http://127.0.0.1:8080/jinquan/1.jpg <br/>
     * 执行: url = replaceIp(url, "192.168.1.1")后，<br/>
     * url值为：http://192.168.1.1:8080/jinquan/1.jpg
     */
    public static String replaceIp(String url, String ip) {
        // 匹配ip的正则表达式
        return url.replaceAll(IP_REGEXP, ip);
    }

    public static String replaceIp(String url) {
        // 匹配ip的正则表达式
        return url.replaceAll(IP_REGEXP, RetrofitClientCL.getInstance().baseUrlChenglu);
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    /**
     * 验证信用卡到期
     */
    public static boolean isCard(String mobiles) {

//        String telRegex =  "/^(?:0?[1-9]|1[0-2])[1-9][0-9]$/" ;
        String telRegex =  "^\\d{4,6}$" ;
        if (TextUtils.isEmpty(mobiles)){
            return false;
        } else {

            return mobiles.matches(telRegex);
        }
    }

    //信用卡安全码
    public static boolean isCardSafeCode(String mobiles) {

        String telRegex =  "^\\d{3,6}$" ;

        if (TextUtils.isEmpty(mobiles)){
            return false;
        } else {

            return mobiles.matches(telRegex);
        }
    }

    public static boolean isValidPhoneNumber(String phoneNumber) {
        if ((phoneNumber != null) && (!phoneNumber.isEmpty())) {
            return Pattern.matches("^1[3-9]\\d{9}$", phoneNumber);
        }
        return false;
    }
    public static boolean isValidCodeNumber(String phoneNumber) {
        if ((phoneNumber != null) && (!phoneNumber.isEmpty())) {
            return Pattern.matches("[0-9]\\d{5}$", phoneNumber);
        }
        return false;
    }
    /**
      *
      * @description 检验身份证号
      *
      */
    
    public static boolean isLegalId(String id) {
        if (id.toUpperCase().matches("(^\\d{15}$)|(^\\d{17}([0-9]|X)$)")) {
            return id.toUpperCase().matches("(^\\d{15}$)|(^\\d{17}([0-9]|X)$)");
        }
        return false;
    }


    public static boolean bankLuhmCheck(String bankno) {
        if (bankno.length() < 16 || bankno.length() > 19) {
            return false;
        }
        return false;
    }


    public static String luhmCheck(String bankno) {
        if (bankno.length() < 16 || bankno.length() > 19) {
            return bankno;
        }
        return bankno;
    }

    //验证银行卡号
    public static boolean checkBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;
    }
    //从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
    public static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    //截取下载地址文件名
    public static String getFileName(String pathandname) {
//        int start = pathandname.lastIndexOf("/");
//        int end = pathandname.lastIndexOf("?");
//        if (start != -1 && end!=-1) {
//            return pathandname.substring(start + 1,end);
//        } else {
//            return null;
//        }

        int start = pathandname.lastIndexOf("/");
        if (start != -1) {
            return pathandname.substring(start + 1);
        } else {
            return null;
        }
    }


    /**
     * 找到html中所有的图片url
     *
     * @param htmlCode
     * @return
     */
    public static String[] returnImageUrlsFromHtml(String htmlCode) {
        List<String> imageSrcList = new ArrayList<String>();
        Pattern p = Pattern.compile("<img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic|\\b)\\b)[^>]*>", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(htmlCode);
        String quote = null;
        String src = null;
        while (m.find()) {
            quote = m.group(1);
            src = (quote == null || quote.trim().length() == 0) ? m.group(2).split("//s+")[0] : m.group(2);
            imageSrcList.add(src);
        }
        if (imageSrcList.size() == 0) {
            return null;
        }
        return imageSrcList.toArray(new String[imageSrcList.size()]);
    }


    public static RequestBody getRequestBody(JSONObject jsonObject) {

        LogUtils.d( jsonObject.toString().replace("\\", ""));
        return RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString().replace("\\", "")
        );
    }

    public static RequestBody getRequestBodyArray(JSONArray jsonObject) {

        LogUtils.d( jsonObject.toString().replace("\\", ""));
        return RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString().replace("\\", "")
        );
    }


    //验证URL是否合法
    public static boolean checkUrl(String url) {
        if (Patterns.WEB_URL.matcher(url).matches()) {
            //符合标准url
            return true;
        } else {
            //不符合标准
            return false;
        }
    }


    public static WebView webX5init(WebView x5WebView) {

        WebSettings webSettings = x5WebView.getSettings();
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置布局，会引起WebView的重新布局（relayout）,默认值NARROW_COLUMNS
        webSettings.setLoadsImagesAutomatically(true);//自动加载图片资源

        //提高渲染的优先级
//        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        //使把图片加载放在最后来加载渲染
//        webSettings.setBlockNetworkImage(true);
        // 开启H5(APPCache)缓存功能
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setJavaScriptEnabled(true);//执行javascript脚本


        //适配手机大小
//        webSettings.setSupportZoom(true);
//        webSettings.setBuiltInZoomControls(true);
//        webSettings.setDisplayZoomControls(false);
//        webSettings.setUseWideViewPort(true);//支持HTML的“viewport”标签或者使用wide viewport //将图片调整到适合webview的大小
//        webSettings.setLoadWithOverviewMode(true);//缩小内容以适应屏幕宽度 // 缩放至屏幕的大小
//        webSettings.setGeolocationEnabled(true);//启用定位

        webSettings.setDomStorageEnabled(true);//启用DOM存储API
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        x5WebView.requestFocus();
        x5WebView.canGoForward();
        x5WebView.canGoBack();

        x5WebView.clearCache(true);
        x5WebView.clearHistory();
        return x5WebView;
    }


    public static String recoverBrace(String name) {
        if (name == null) {
            return null;
        }
        //转义字符要使用\\转义或使用"\\\\" +
        String recoverStr = name.replaceAll("\\{ ", "").replaceAll("\\ } ", "");//;
        return recoverStr;
    }


    public static boolean checkAliPayInstalled(Context context) {

        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }


    public static void goodsType(int getGoodsType, TextView tvLikeMoney, String goodsPrice) {

        switch (getGoodsType) {

            case 0:
            case 1:
            case 2:
            case 3:
            case 5:
            case 6:
                tvLikeMoney.setText("¥" + formatZeroNumber(goodsPrice));
                break;
            case 4:
                tvLikeMoney.setText(formatZeroNumber(goodsPrice) + "积分");
                break;
            default:
                tvLikeMoney.setText("¥" + formatZeroNumber(goodsPrice));
                break;


        }


    }


    //获取 cpu 信息
    public static String getCpuInfo() {
        String[] abis = new String[]{};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            abis = Build.SUPPORTED_ABIS;
        } else {
            abis = new String[]{Build.CPU_ABI, Build.CPU_ABI2};
        }
        StringBuilder abiStr = new StringBuilder();
        for (String abi : abis) {
            abiStr.append(abi);
            abiStr.append(',');
        }

        return abiStr.toString();
    }

    // 判断是否模拟器
    public static boolean isEmulator() {
        String abiStr = getCpuInfo();
        if (abiStr != null && abiStr.length() > 0) {
            boolean isSupportX86 = false;
            boolean isSupportArm = false;

            if (abiStr.contains("x86_64") || abiStr.contains("x86")) {
                isSupportX86 = true;
            }
            if (abiStr.contains("armeabi") || abiStr.contains("armeabi-v7a") || abiStr.contains("arm64-v8a")) {
                isSupportArm = true;
            }
            if (isSupportX86 && isSupportArm) {
                //同时拥有X86和arm的判断为模拟器。
                return true;
            }
        }
        return false;
    }

    /**
     * 检查手机是否有sim卡
     */
    public static boolean checkSim(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getSimOperator();
        if (TextUtils.isEmpty(operator)) {
            return false;
        }
        return true;
    }


    /**
     * 获取设备运营商
     * @return ["中国电信CTCC":"3"]["中国联通CUCC:"2"]["中国移动CMCC":"1"]["other":"0"]
     */
    public static String getOperatorType(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getNetworkOperator();
        String opeType = "0";
        // 中国联通
        if ("46001".equals(operator) || "46006".equals(operator) || "46009".equals(operator)) {
            opeType = "2";
            // 中国移动
        } else if ("46000".equals(operator) || "46002".equals(operator) || "46004".equals(operator) || "46007".equals(operator)) {
            opeType = "1";
            // 中国电信
        } else if ("46003".equals(operator) || "46005".equals(operator) || "46011".equals(operator)) {
            opeType = "3";
        }
        return opeType;
    }


        public static String urlEncodeURL(String str) {
        try {
            String result = URLEncoder.encode(str, "UTF-8");
            result = result.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");//+实际上是 空格 url encode而来
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

//    private static boolean isNumberd(String str) {
//
//        return StringUtils.isNumeric(str);
//
//    }


    private static boolean isNumber(String str) {

        try {

            Integer.parseInt(str);

            return true;

        } catch (NumberFormatException e) {

            e.printStackTrace();

            return false;

        }

    }

    public static boolean compareMoney(String value1, String value2) {
        BigDecimal b1 = new BigDecimal(value1);
        BigDecimal b2 = new BigDecimal(value2);
        return b1.compareTo(b2) != -1;
    }


    /**
     * 获取自己应用内部的版本号
     */
    public static int getVersionCode(Context context) {
        PackageManager manager = context.getPackageManager();
        int code = 0;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            code = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }


    /**
     * 获取自己应用内部的版本名
     */
    public static String getVersionName(Context context) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

    public static String getVersionName(Context context,String packageName) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(packageName, 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

     /**
       *
       * @description 去掉小数点后面是0的数字
       *
       */

    public static String formatZeroNumber(String number) {

        if(number == null){

            return "";

        }

        if(number.indexOf(".") > 0){

            //正则表达

            number = number.replaceAll("0+?$", "");//去掉后面无用的零

            number = number.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点

        }

        if(number.indexOf(".") > 0){

            BigDecimal b = new BigDecimal(number);

            return String.valueOf(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        }else{

            return number;

        }

    }

    //除整为0 显示的数
    public static String doubleTrans2(double num){
        if(Math.round(num)-num==0){
//            LogUtils.d("整形显示="+ String.valueOf((long) num));
            return String.valueOf((long) num);
        }
        return String.valueOf(num);
    }




    /**
     *
     * @description 去掉小数点后面是0的数字
     *
     */

    public static String saveformatThreeNumber(String number) {

        if(number == null){

            return "";

        }

        if(number.indexOf(".") > 0){

            //正则表达

            number = number.replaceAll("0+?$", "");//去掉后面无用的零

            number = number.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点

        }

        if(number.indexOf(".") > 0){

            BigDecimal b = new BigDecimal(number);

            return String.valueOf(b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue());

        }else{

            return number;

        }

    }



    public static String formatZeroNumberPoint(String number) {

        if(number == null){

            return "";

        }

        if(number.indexOf(".") > 0){

            //正则表达

            number = number.replaceAll("0+?$", "");//去掉后面无用的零

            number = number.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点

        }

        if(number.indexOf(".") > 0){

            BigDecimal b = new BigDecimal(number);

            return String.valueOf(b.setScale(0, BigDecimal.ROUND_HALF_UP).intValue());

        }else{

            return number;

        }

    }
    public static boolean isEmpty(final Object obj) {
        if (obj == null) {
            return true;
        }
      return true;
    }
//    保留N位小数，下面以保留两位小数为例：


    public static double formatNumber(double number){

        String result = "";

        try {

            DecimalFormat decimalFormat =new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.

            result = decimalFormat.format(number);//format 返回的是四舍五入后的字符串

        } catch (Exception e){

            LogUtils.e(e.getMessage());

        }

        return Double.valueOf(result);

    }

    public static String formatEnum(String str){
        BigDecimal db = new BigDecimal(str);
        return   db.toPlainString();
    }


    public static String getStarMobile(String mobile){

        if(!TextUtils.isEmpty(mobile)){
            if(mobile.length()>=11){
                return  mobile.substring(0,3)+"****"+mobile.substring(7,mobile.length());
            }else {
                return "";
            }
        }

        return mobile;
    }

    public static String dealRateStr(String rateStr) {
        int i = rateStr.indexOf(".");
        //如果没有小数点不
        if (i == -1) {
            return rateStr + ".00";
        }
        //获取小数点的位置
        int num = rateStr.indexOf(".");
        //获取小数点后面的数字 是否有两位 不足两位补足两位
        String afterData = rateStr.replace(rateStr.substring(0, num + 1), "");
        if (afterData.length() < 2) {
            afterData = afterData + "0";
        }
        return rateStr.substring(0, num) + "." + afterData.substring(0, 2);
    }

    public static void  noNetWork( Context context,LinearLayout llLoadingData, LinearLayout llLoadingNoData, ImageView ivNoData, TextView tvNoData){

        if(NetworkUtil.isNetworkEnabled(context)){
            ivNoData.setBackground(context.getResources().getDrawable(R.drawable.icon_error));
            tvNoData.setText("暂无数据，点击重新获取");
        }else {
            ivNoData.setBackground(context.getResources().getDrawable(R.drawable.bg_no_net));
            tvNoData.setText("网络不可用，点击重新获取");
        }
        llLoadingNoData.setVisibility(View.VISIBLE);
        llLoadingData.setVisibility(View.GONE);
    }


    public  static  void  setNetWork (Context context){
        if(!NetworkUtil.isNetworkEnabled(context)){
            ToastUtils.show(context.getResources().getString(R.string.network_error_no_net));
            return;
        }
    }

//    public static final class PreloadTarget<Z> extends CustomTarget<Z> {
//        private static final int MESSAGE_CLEAR = 1;
//        private static final Handler HANDLER =
//                new Handler(
//                        Looper.getMainLooper(),
//                        new Handler.Callback() {
//                            @Override
//                            public boolean handleMessage(Message message) {
//                                if (message.what == MESSAGE_CLEAR) {
//                                    ((PreloadTarget<?>) message.obj).clear();
//                                    return true;
//                                }
//                                return false;
//                            }
//                        });
//
//        @Override
//        public void onResourceReady(@NonNull Z resource, @Nullable Transition<? super Z> transition) {
//            //资源下载成功直接clean，如果其他地方没有引用会直接丢到Lru缓存里面
//            HANDLER.obtainMessage(MESSAGE_CLEAR, this).sendToTarget();
//        }
//
//        @Override
//        public void onLoadCleared(@Nullable Drawable placeholder) {
//
//        }
//    }


    public static Bitmap createQrcodeBitmap(String content, ImageView imageView) {
        if (TextUtils.isEmpty(content)) {
            return null;
        }
        int width = imageView.getWidth() * 2; // 二维码图片的宽度
        int height = imageView.getHeight() * 2; // 二维码图片的高度
        int margin = 2; // 二维码图片的空白边距
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.MARGIN, margin); // 设置空白边距
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符编码格式
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 设置容错率
        try {
            // 根据配置参数生成位矩阵对象
            BitMatrix bitMatrix = new QRCodeWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);
            // 创建像素数组，并根据位矩阵对象为数组元素赋色值
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) { // 返回true表示黑色色块
                        pixels[y * width + x] = Color.BLACK;
                    } else { // 返回false表示白色色块
                        pixels[y * width + x] = Color.WHITE;
                    }
                }
            }
            // 创建位图对象，并根据像素数组设置每个像素的色值
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}











